package com.jy.rhin.application.document;

import cn.hutool.core.text.CharSequenceUtil;
import cn.org.chiss.rhin._2015.base.object.AdhocQuery;
import cn.org.chiss.rhin._2015.base.object.Slot;
import cn.org.chiss.rhin._2015.document.management.DocumentStoredQuery;
import cn.org.chiss.rhin._2015.document.management.DocumentStoredQueryResponse;
import com.jy.rhin.config.RhinFaultSubCode;
import com.jy.rhin.facade.ws.basic.wsEntry.exception.RhinWSException;
import com.jy.rhin.infra.exception.RhinAggrErrorType;
import com.jy.rhin.infra.exception.RhinAggrException;
import com.jy.rhin.support.polymorphism.convertor.DocumentQueryHandler;
import com.jy.rhin.support.polymorphism.convertor.DocumentQueryHandlerFactory;
import com.jy.rhin.support.util.Asserts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author dhl
 * @date 2022/6/22
 * @Description
 */
@Slf4j
@Service
public class DocumentQueryApplication {

    @Resource
    DocumentQueryHandlerFactory documentQueryHandlerFactory;

    /**
     * 文档索引实现
     *
     * @param message
     * @return
     */
    public DocumentStoredQueryResponse getDocumentStoredQueryResponse(DocumentStoredQuery message) {
        AdhocQuery query = message.getAdhocQuery();
        String funName;
        DocumentQueryHandler queryHandler;
        try {
            Asserts.nonNull(query, RhinAggrErrorType.DOCUMEN_STORED_QUERY_PARAM_INCORRECT_FAULT);
            Asserts.nonNull(query.getId(), RhinAggrErrorType.DOCUMEN_STORED_QUERY_PARAM_INCORRECT_FAULT);
            Asserts.nonNull(query.getSlot(), RhinAggrErrorType.DOCUMEN_STORED_QUERY_PARAM_INCORRECT_FAULT);

            funName = query.getId().getValue();
            //校验id内容非空并拿到可用方法名
            Asserts.notEmpty(funName, RhinAggrErrorType.DOCUMEN_STORED_QUERY_PARAM_INCORRECT_FAULT);

            //校验查询条件非空
            List<Slot> slotList = query.getSlot();
            Asserts.notEmpty(slotList, RhinAggrErrorType.DOCUMEN_STORED_QUERY_PARAM_INCORRECT_FAULT);

            //校验查询的方法名在规定的11个查询接口中
            funName = getFunName(funName);
            queryHandler = documentQueryHandlerFactory.getIns(funName);
        } catch (RhinAggrException ex) {
            throw new RhinWSException(ex.getErrorType().getCode(), ex.getErrorType().getMsg());
        }
        DocumentStoredQueryResponse response;
        try {
            response = queryHandler.documentStoredQuery(query.getSlot());
        } catch (Exception ex) {
            throw new RhinWSException(RhinFaultSubCode.RetrieveDocumentSetFault);
        }

        return response;
    }

    /**
     * 分割取最后一节字符串并首字母小写
     *
     * @param funName
     * @return
     */
    private String getFunName(String funName) {
        String[] nameArray = funName.trim().split(":");
        funName = nameArray[nameArray.length - 1];
        funName = CharSequenceUtil.lowerFirst(funName);
        return funName;
    }
}
